package com.pospi.pai.yunpos.more;

import android.app.Activity;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.ColorDrawable;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.TextView;
import android.widget.Toast;

import com.digi.module.Printer.IPrinter;
import com.digi.port.Printer;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.google.zxing.BarcodeFormat;
import com.king.zxing.util.CodeUtils;
import com.lany.sp.SPHelper;
import com.pospi.callbacklistener.HttpCallBackListener;
import com.pospi.dao.GoodsDao;
import com.pospi.dto.GoodsDto;
import com.pospi.dto.ScalesBeen;
import com.pospi.http.HttpConnection;
import com.pospi.pai.yunpos.R;
import com.pospi.pai.yunpos.base.Base2Activity;
import com.pospi.pai.yunpos.been.SupBeen;
import com.pospi.pai.yunpos.cash.PointActivity;
import com.pospi.pai.yunpos.login.Constant;
import com.pospi.pai.yunpos.util.BillUtil;
import com.pospi.pai.yunpos.util.ScaleUItil;
import com.pospi.pai.yunpos.util.SocketReponse;
import com.pospi.pai.yunpos.util.SocketUtil;
import com.pospi.util.App;
import com.pospi.util.DoubleSave;
import com.pospi.util.StarPrintHelper;
import com.pospi.util.TabPrintHelper;
import com.pospi.util.constant.URL;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Created by acer on 2018/9/7.
 */

public class ScaleGoodsActivity extends Base2Activity implements AdapterView.OnItemClickListener {
    @Bind(R.id.list_goods)
    ListView list_goods;
    @Bind(R.id.et_search)
    EditText et_search;
    @Bind(R.id.tv_fl)
    TextView tv_fl;
    @Bind(R.id.parent)
    LinearLayout parent;
    private GoodsDao dao;
    private MyAdapter adapter;
    private List<SupBeen> fl_Beens = new ArrayList<>();//分类
    private List<SupBeen> pp_Beens = new ArrayList<>();//品牌
    private List<SupBeen> md_Beens = new ArrayList<>();//门店
    private String market = "";
    private String cat = "";
    private String brand = "";
    private String supid = "";
    private long time = 0;



    Handler handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    closeLodindDialog();
                    print("发送完成!");

                    break;
                case 2:
                    closeLodindDialog();
                    print("无法连接到电子秤，请检查设备是否处于同一网络中");
                    break;
                case 3:
                    closeLodindDialog();
                    break;
            }
        }
    };
    private EditText good_weight;


    private void print(String msg) {
        new AlertDialog.Builder(this)
                .setTitle("提示")
                .setMessage(msg).setPositiveButton("确定", null).show();
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentLayout(R.layout.activity_sacles);
        ButterKnife.bind(this);
        dao = new GoodsDao(this);
        setTitle("电子秤商品管理");
        setMenuText("发送到电子秤");
        scaleUItil = new ScaleUItil(this);

        down();
        setMenuTextSize(18);
        init();
    }

    private void init() {
        List<ScalesBeen> beens = App.getInstance().getDaoSession().getScalesBeenDao().loadAll();
        scalesBeens.addAll(beens);
        adapter = new MyAdapter();
        list_goods.setAdapter(adapter);
        list_goods.setOnItemClickListener(this);
    }

    @Override
    public void onMenuClick(View view) {
        super.onMenuClick(view);
        showMultiChioceDialog();
    }

    private List<ScalesBeen> scalesBeens = new ArrayList<>();
    private void connect(String ip){
        new SocketUtil().initThread(dtos, ip);

    }

    @OnClick({R.id.iv_search ,R.id.tv_fl})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.iv_search:
                dtos.clear();
                List<GoodsDto> list = dao.findGoodsByFilter(et_search.getText().toString().trim(),cat);
                if (list.size() > 0) {
                    dtos.addAll(list);
                } else {
                    Toast.makeText(this, "未查询到数据", Toast.LENGTH_SHORT).show();
                }
                time = dtos.size() * 210;
                adapter.notifyDataSetChanged();
                break;
            case R.id.tv_fl:
                showfl(tv_fl);
                break;
        }
    }
    //下载分类
    private void down() {
        Map<String, String> params = new HashMap<>();
        params.put("logid", SPHelper.getInstance().getString(Constant.USER_ID));
        params.put("sysid", SPHelper.getInstance().getString(Constant.SYS_ID));
        params.put("model", "base.mselect");
        params.put("fun", "getlastgoodscat");
        Log.i("goods", params.toString());
        new HttpConnection().postNet(params, new HttpCallBackListener() {
            @Override
            public void CallBack(String Response) {
                Log.i("login", Response);
                try {
                    JSONObject jsonObject = new JSONObject(Response);
                    JSONArray result = jsonObject.getJSONArray("result");
                    fl_Beens = new Gson().fromJson(result.toString(), new TypeToken<List<SupBeen>>() {
                    }.getType());
                    fl_Beens.add(new BillUtil().getNewSup());
                } catch (JSONException e) {

                    e.printStackTrace();
                }
            }
        });


    }
    private List<GoodsDto> dtos = new ArrayList<>();

    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        showSetWeightPopupWindow(dtos.get(position));
    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return dtos.size();
        }

        @Override
        public Object getItem(int i) {
            return dtos.get(i);
        }

        @Override
        public long getItemId(int i) {
            return i;
        }

        @Override
        public View getView(int i, View view, ViewGroup viewGroup) {
            Holder holder;
            if (view == null) {
                holder = new Holder();
                view = LayoutInflater.from(ScaleGoodsActivity.this).inflate(R.layout.scale_bill_item, null);
                holder.name = view.findViewById(R.id.name);
                holder.tv_dj = view.findViewById(R.id.tv_dj);
                holder.tv_dw = view.findViewById(R.id.tv_dw);
                holder.tv_xh = view.findViewById(R.id.tv_xh);
                holder.code = view.findViewById(R.id.code);
                holder.tv_plu = view.findViewById(R.id.tv_plu);
                view.setTag(holder);
            } else {
                holder = (Holder) view.getTag();
            }
            GoodsDto bill = dtos.get(i);
            holder.name.setText(bill.getName());
            holder.code.setText(bill.getCode());
            holder.tv_dj.setText(String.valueOf(bill.getPrice()));
            holder.tv_dw.setText(bill.getUnit());
            holder.tv_xh.setText(String.valueOf(i + 1));
            holder.tv_plu.setText(bill.getPlu());
            return view;
        }

        class Holder {
            TextView name;
            TextView tv_dj;
            TextView tv_dw;
            TextView code;
            TextView tv_xh;
            TextView tv_plu;

        }
    }

    private void showfl(View v) {
        List<String> strings = new ArrayList<>();
        strings.clear();
        for (SupBeen been : fl_Beens) {
            strings.add(been.getName());
        }
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_yyy, null);
        final PopupWindow yyyPopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        yyyPopupWindow.setBackgroundDrawable(new BitmapDrawable());
        yyyPopupWindow.setFocusable(true);
        contentView.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
        int height = contentView.getMeasuredHeight();
        int width = contentView.getMeasuredWidth();
        int[] location = new int[2];
        v.getLocationOnScreen(location);
//        yyyPopupWindow.showAtLocation(v, Gravity.NO_GRAVITY, (location[0] + v.getWidth() / 2) - width / 2, location[1]);
        yyyPopupWindow.showAsDropDown(v);

        ListView listView = contentView.findViewById(R.id.yyy_list);
        listView.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings));
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                tv_fl.setText(fl_Beens.get(position).getName());
                cat = fl_Beens.get(position).getId();
                yyyPopupWindow.dismiss();
            }
        });
    }
    public void showMultiChioceDialog() {
        final String[] items = new String[scalesBeens.size()];/*设置多选的内容*/
        final boolean[] checkedItems = new boolean[scalesBeens.size()];/*设置多选默认状态*/
        for (int i = 0; i < scalesBeens.size(); i++) {
            items[i] = scalesBeens.get(i).getNum() +"-"+scalesBeens.get(i).getName()+ "[" + scalesBeens.get(i).getIp() + "]";
            checkedItems[i] = false;
        }
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("请选择电子秤");
        builder.setMultiChoiceItems(items, checkedItems, new DialogInterface.OnMultiChoiceClickListener() {/*设置多选的点击事件*/
            @Override
            public void onClick(DialogInterface dialog, int which, boolean isChecked) {
                checkedItems[which] = isChecked;
            }
        });
        builder.setPositiveButton("发送", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                boolean chooes = false;
                for (int j = 0;j<checkedItems.length;j++) {
                    if (checkedItems[j]) {
                        chooes = true;
                    }
                }
                if (!chooes) {
                    Toast.makeText(ScaleGoodsActivity.this, "请选择电子秤", Toast.LENGTH_SHORT).show();
                    return;
                }

                showLodingDialog("发送中...");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        try {
                            Thread.sleep(time);

                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }finally {
                            Message message = Message.obtain();
                            message.what = 1;
                            handler.sendMessage(message);
                        }
                    }
                }).start();
                for (int j = 0;j<checkedItems.length;j++) {
                    if (checkedItems[j]) {
                        connect(scalesBeens.get(j).getIp());
                    }
                }

            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.setCancelable(false);
        builder.show();
    }

    private ScaleUItil scaleUItil;
    private void showSetWeightPopupWindow(final GoodsDto goodsdto) {
//        final SerialPortManager portManager = new SerialPortManager();
//        portManager.openSerialPort(new File("/dev/ttyHSL1"), 9600);
//        byte[] b = new byte[]{0x04,0x02,0x31,0x30,0x03};
//        portManager.sendBytes(b);
//        BluetoothHelper.connect(this);
        View contentView = LayoutInflater.from(this).inflate(R.layout.dialog_dzc, null);
       final PopupWindow mPricePopupWindow = new PopupWindow(contentView, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        mPricePopupWindow.setBackgroundDrawable(new BitmapDrawable());
        mPricePopupWindow.setFocusable(true);
        // 实例化一个ColorDrawable颜色为半透明
        ColorDrawable dw = new ColorDrawable(0xb0000000);
        backgroundAlpaha(this, 0.5f);

        TextView sure = (TextView) contentView.findViewById(R.id.btn_sure);
        sure.setText("打印");
        CheckBox tab_box = contentView.findViewById(R.id.tab_box);
        tab_box.setVisibility(View.GONE);
//        text_num = (TextView) contentView.findViewById(R.id.text_num);
        good_weight = (EditText) contentView.findViewById(R.id.et_sl);
        TextView tv_singlePrice = contentView.findViewById(R.id.et_money);
        ImageView iv_dismiss = contentView.findViewById(R.id.iv_dismiss);
        TextView tvName = (TextView) contentView.findViewById(R.id.tv_name);
        TextView tvPrice = (TextView) contentView.findViewById(R.id.tv_price);
        TextView tv_no = contentView.findViewById(R.id.tv_no);

        TextView clear_weight = (TextView) contentView.findViewById(R.id.tv_cz);
        TextView tv_qp = contentView.findViewById(R.id.tv_qp);
        tv_qp.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                scaleUItil.touchTare();
            }
        });

        iv_dismiss.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPricePopupWindow.dismiss();
            }
        });
//        TextView choose_type = contentView.findViewById(R.id.choose_type);
//        choose_type.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //手动输入
////                portManager.closeSerialPort();
//                numberAdd = "";
//                good_weight.setText("");
//            }
//        });

        if (Build.MODEL.equals(URL.MODEL_T1) || Build.MODEL.equals(URL.MODEL_T2)||Build.MODEL.equals(URL.MODEL_D1)) {
        } else {
            scaleUItil.showWight(good_weight,tv_singlePrice,goodsdto.getPrice());
        }
        tv_no.setText(goodsdto.getCode());
        tvName.setText(goodsdto.getName());
        tvPrice.setText("单价："+goodsdto.getPrice() + "元/kg");
//        tv_singlePrice.setText(goodsdto.getPrice()+"元/500g");
//        jian.setOnClickListener(listener);
//        jia.setOnClickListener(listener);
//        clear.setOnClickListener(listener);
        clear_weight.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                numberAdd = "";
                good_weight.setText("");
                scaleUItil.zeroScale();
            }
        });
        sure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                if (mPricePopupWindow != null) {
                    mPricePopupWindow.dismiss();
                }
//                mPricePopupWindow.dismiss();
                String weight = good_weight.getText().toString().trim();
                if (weight.equals("") || weight.equals("UF") || weight.equals("OF")) {
                    numberAdd = "";
                    good_weight.setText("");
                    return;
                }

                goodsdto.setNum(DoubleSave.doubleSaveThree(Double.parseDouble(weight)));
                new TabPrintHelper(ScaleGoodsActivity.this, goodsdto).printTab();


                numberAdd = "";
                good_weight.setText("");

            }
        });

        mPricePopupWindow.showAtLocation(parent, Gravity.CENTER, 0, 0);
        mPricePopupWindow.setOnDismissListener(new PopupWindow.OnDismissListener() {
            @Override
            public void onDismiss() {
                scaleUItil.stopShow();
                backgroundAlpaha(ScaleGoodsActivity.this, 1.0f);
                numberAdd = "";
            }
        });

    }



    /**
     * 设置添加屏幕的背景透明度
     **/
    public void backgroundAlpaha(Activity context, float bgAlpha) {
        WindowManager.LayoutParams lp = context.getWindow().getAttributes();
        lp.alpha = bgAlpha;
        context.getWindow()
                .addFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);
        context.getWindow().setAttributes(lp);
    }
    /**
     * 设置价格窗口的数字键点击事件
     */
    private String numberAdd = "";

    public void numberClick(View view) {
        TextView tv = (TextView) view;
        if (numberAdd.isEmpty()) {
            if (view.getId() != R.id.dian) {
                numberAdd += tv.getText().toString();
            }
        } else {
            if (numberAdd.equals("0") && view.getId() == R.id.dian) {
                numberAdd = tv.getText().toString();
            } else {
                numberAdd += tv.getText().toString();
            }
        }
        good_weight.setText(numberAdd);
    }

}
